from rest_framework.response import Response
from rest_framework import status
from datetime import *
from userAccount.models import *
import random
import string
import hashlib
import requests
import re


def response_origin(*args, **kwargs):
    re = Response(*args, **kwargs)
    re['Access-Control-Allow-Origin'] = '*'
    re["Access-Control-Allow-Credentials"] = "true"
    re['Content-Type'] = 'application/json'
    return re


def is_data(request, method, *args, **kwargs):
    """
    获取request中的表单数据，验证数据无误返回一个字典，如果有异常数据会返回一个Response对象
    调用格式如：is_valid(request, "POST", "uid", username=None, role=None)
    :param request:
    :param method:
    :param kwargs:
    :return:
    """
    keys = list(args) + list(kwargs.keys())
    for key in keys:  # 设置第一种获取方式（获取Form表单格式数据）
        if method == "GET":
            value = request.GET.get(key, None)
        elif method == "POST":
            value = request.POST.get(key, None)
        elif method == "PUT":
            # value = request.PUT.get(key, None)
            value = request.data[key]

        if not value:  # 设置第二种获取方式（获取转为JSON的数据格式）
            value = request.data[key]

        if not value:  # 为空则返回
            return response_origin({"message": "Parameter '%s' cannot be empty!" % key},
                                   status=status.HTTP_400_BAD_REQUEST)
        else:
            kwargs[key] = value
    return kwargs


def only_num():
    nowtime = datetime.now().strftime("%Y%m%d%H%M%S")  # 生成当前的时间
    random_num = random.randint(0, 100)  # 生成随机数n,其中0<=n<=100
    if random_num <= 10:
        random_num = str(0) + str(random_num)
    uniqueNum = str(nowtime) + str(random_num)
    return uniqueNum[5:15]


def get_ip(request):
    """
    获取用户的IP地址
    """
    try:
        real_ip = request.META['HTTP_X_FORWARDED_FOR']
        regip = real_ip.split(",")[0]
    except:
        try:
            regip = request.META['REMOTE_ADDR']
        except:
            regip = ""
    return regip


def make_standard_dict():
    """
    返回标准格式的字典
    :return:
    """
    context = {
        'status': 0,
        'errmsg': '',
        'payload': {}
    }
    return context


def make_false_dict():
    '''
    返回标准错误格式的字典
    :return:
    '''
    context = {
        'status': 1,
        'errmsg': '',
        'payload': {}
    }
    return context


def hash_password(pwd):
    """
    讲明文密码进行加密
    :param pwd: 明文密码
    :return: 经过sha256加密的密码
    """
    sha = hashlib.sha256()
    sha.update(pwd.encode("utf-8"))
    return sha.hexdigest()


def check_phone(phone,code):
    # url = "http://final-msg:80/checkMsgCode?phone={phone}&code={code}".format(phone=phone, code=code)
    url = 'http://beacon-msg-info/info/checkMsgCode'
    data = {"phone": "%s" % phone,
            "code": "%s" % code,
            }
    r = requests.get(url,data)
    # r = requests.get(url)
    data = r.json()
    # if len(TbUser.objects.filter(nickname=account)) != 0:
    #     raise Exception("该账号已存在")
    return data


def check_mobile(phone):
    if not re.compile(r'[1][34578]\d{9}$').match(phone):
        raise Exception("请输入正确的手机号码")
    if len(TUserInfo.objects.filter(f_mobile_phone=phone)) != 0:
        raise Exception("该手机号已被绑定")
    return True


def check_account(account):
    if len(TUserInfo.objects.filter(f_nickname=account)) != 0:
        raise Exception("用户昵称已存在")
    return True
#
#
# # 检查邮箱是否已注册
# def check_email(email):
#     if len(TbUserExtended.objects.filter(email=email)) != 0:
#         raise Exception("该邮箱已注册")
#     return True


# 检查密码是否规范
def verify_password(pwd):
    number = False  # 包含數字
    letter = False  # 包含字母
    upper = False  # 包含大寫字母
    lower = False  # 包含小寫字母
    special = False  # 特殊字符
    other = False  # 其他符號

    if len(pwd) < 12:
        raise Exception('密碼長度不小於12位')
    for i in pwd:  # 遍历密码
        if (i >= '\u0041' and i <= '\u005a') or (i >= '\u0061' and i <= '\u007a'):  # 對密碼中所有英文字母遍歷（判斷大小寫）
            letter = True
            if i.islower():
                lower = True
            if i.isupper():
                upper = True
        if i >= '\u0030' and i <= '\u0039':  # 判斷密碼中是否有數字
            number = True
        if i == '\u0020' or i == '\u002f' or i == '\u005c' or i == '\u007c':  # 密碼中不能包含/ \ |
            special = True
        if i in string.punctuation:  # 密码必须包含特殊字符
            other = True
    if letter == False:
        raise Exception('密碼中必須包含字母')
    if upper == False:
        raise Exception('密碼中必須包含大寫字母')
    if lower == False:
        raise Exception('密碼中必須包含小寫字母')
    if number == False:
        raise Exception('密碼中必須包含數字')
    if special == True:
        raise Exception(r'密碼中不能包含/,\,|,空格')
    if other == False:
        raise Exception('密碼中必须包含特殊字符')
    return True


def verify_code():
    """
    随机生成一个6位数的验证码
    :return:
    """
    code = ''
    for i in range(8):
        c_init = str(int(random.randint(1, 9)))
        code += c_init
    return "150"+code
